//
//  YFSelectImageController.swift
//  微博
//
//  Created by 余仿 on 16/4/17.
//  Copyright © 2016年 YF. All rights reserved.
//

import UIKit

let maxPictureCount = 9
let pictureMargin:CGFloat = 3
let pictureCount = 4
let pictureWidth:CGFloat = (screenWidth - CGFloat(pictureCount + 1) * pictureMargin) / CGFloat(pictureCount)

private let selectedImageCell = "selectedImageCell"

class YFSelectImageController: UICollectionViewController {


    var imageList:[UIImage] = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(YFImageCell.self, forCellWithReuseIdentifier: selectedImageCell)

    }

    init(){

        let flowLayout = UICollectionViewFlowLayout()
        //设置属性
        //图片框大小
        flowLayout.itemSize = CGSize(width: pictureWidth, height: pictureWidth)
        //设置行列间距
        flowLayout.minimumInteritemSpacing = pictureMargin
        flowLayout.minimumLineSpacing = pictureMargin
        //设置组的边距
        flowLayout.sectionInset = UIEdgeInsets(top: pictureMargin, left: pictureMargin, bottom: 0, right: pictureMargin)

        super.init(collectionViewLayout: flowLayout)
        //设置集合视图的颜色
        collectionView?.backgroundColor = UIColor.whiteColor()

    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }



}


// MARK: - 数据源方法
extension YFSelectImageController{

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        //如果只写加一每次点击加号,都会多创建一个,即使达到最大张数
        let delta = imageList.count >= maxPictureCount ? 0:1
        return imageList.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        //TODO:此处强制解包是否安全
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(selectedImageCell, forIndexPath: indexPath) as! YFImageCell

        cell.backgroundColor = randomColor

        cell.delegate = self

        if indexPath.item == imageList.count{
            //加载最后一个,设置图片为nil
            cell.img = nil
            return cell

        }else{
            cell.img = imageList[indexPath.item]
        }


        return cell
    }


}

// MARK: - cell的代理方法
extension YFSelectImageController:YFImageCellDelegate{

    func addImageBtnDidClick() {
        print("VC  添加")
        //1.弹出系统的相片选择控制器
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){

            print("对不起,相册不可用")

            return
        }

        let pickerVc = UIImagePickerController()

        //2.监听图片控制器的行为,设置代理
        pickerVc.delegate = self

        //是否可以编辑图片,默认是不可以编辑的
        pickerVc.allowsEditing = true

        presentViewController(pickerVc, animated: true, completion: nil)

    }

    func deleteImageBtnDidClick(cell:YFImageCell) {
        print("VC 删除")

        //根据cell获取角标
        let indexPath = collectionView!.indexPathForCell(cell)

        //移除模型
        imageList.removeAtIndex(indexPath!.item)

        //刷新数据
        collectionView?.reloadData()

    }

}

/*
    Cannot assign value of type 'YFSelectImageController' to type 'protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>?
*/

// MARK: - 图片选择控制器的代理方法
extension YFSelectImageController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //可以获得点击的图片
        print(image)

        //将图片添加到图片数组中
        imageList.append(image)

        //销毁图片选择控制器
        dismissViewControllerAnimated(true, completion: nil)

        //刷新collectionView
        collectionView?.reloadData()

        print(editingInfo)
    }

}




    /// MARK:自定义cell
    class YFImageCell: UICollectionViewCell {

        var delegate:YFImageCellDelegate?

        //MARK:绑定数据
        var img:UIImage?{

            didSet{

                deleteBtn.hidden = img == nil
                addBtn.setImage(img, forState: .Normal)

                //如果按钮没有图片,就隐藏,如何做?
            }
        }

        //MARK:图片按钮
        private lazy var addBtn:UIButton = UIButton(imageName: nil, title: nil, target: self, action: "addCellDidClick",bgImage:"compose_pic_add")

        //MARK:关闭按钮
        private lazy var deleteBtn:UIButton = UIButton(imageName: nil, title: nil, target: self, action: "deleteBtnDidClick", bgImage: "compose_photo_close")

        //MARK:初始化方法
        override init(frame: CGRect) {
            super.init(frame: frame)

            //MARK:搭建界面
            setupUI()

        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        //MARK:搭建界面
        private func setupUI(){

            //默认的填充模式是填满,长图或者宽图会变形,需要设置填充模式
            addBtn.imageView?.contentMode = .ScaleAspectFill

            contentView.addSubview(addBtn)

            contentView.addSubview(deleteBtn)

            //布局子控件
            addBtn.snp_makeConstraints { (make) -> Void in
                make.edges.equalTo(contentView)
            }

            deleteBtn.snp_makeConstraints { (make) -> Void in
                make.top.right.equalTo(contentView)
            }
        }

        //MARK:添加按钮的点击事件
        @objc private func addCellDidClick(){
            print("点击了cell中的添加")
            //1.弹出系统的相册控制器
            //调用VC的协议方法
            //如果按钮已经有图片了,直接返回
            if img != nil{
                print("已经有图片了")
                return
            }

            delegate?.addImageBtnDidClick?()
            
        }
        
        //MARK:删除按钮的点击事件
        @objc private func deleteBtnDidClick(){
            print("点击了cell中的删除")

            //根据btn获取indexPath

            delegate?.deleteImageBtnDidClick?(self)

        }
        
        
    }





//MARK:声明协议方法
@objc  protocol YFImageCellDelegate:NSObjectProtocol{

    optional func addImageBtnDidClick()

    optional func deleteImageBtnDidClick(cell:YFImageCell)

}





